﻿using System;
using System.Net;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using NAnt.Core;
using NAnt.Core.Attributes;

namespace NAnt.Microsoft.CRM.ThirdParty.Tasks
{
    [TaskName("crmcustdeploy")]
    public class DeployCustomisationsTask : Task
    {

        [TaskAttribute("crmserver", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string CrmServer { get; set; }

        [TaskAttribute("username", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string Username { get; set; }

        [TaskAttribute("password", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string Password { get; set; }

        [TaskAttribute("domain", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string Domain { get; set; }

        [TaskAttribute("file", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string ImportFile { get; set; }

        [TaskAttribute("org", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string Organisation { get; set; }

        [TaskAttribute("port", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string Port { get; set; }

        [TaskAttribute("username", Required = true)]
        [BooleanValidator]
        public bool Publish { get; set; }

        protected override void ExecuteTask()
        {

            Project.Log(Level.Info, "Creating Connection");

            CrmAuthenticationToken token = new CrmAuthenticationToken();
            token.AuthenticationType = 0;
            token.OrganizationName = Organisation;

            CrmService crmservice = new CrmService();
            crmservice.Url = String.Format("http://{0}:{1}/mscrmservices/2007/crmservice.asmx",CrmServer,Port);
            crmservice.Credentials = new NetworkCredential(Username,Password,Domain);
            crmservice.CrmAuthenticationTokenValue = token;

            Deploy(crmservice);
        }

        public void Deploy(CrmService service)
        {
            Project.Log(Level.Info, "About to deploy");

            ImportAllXmlRequest importRequest = new ImportAllXmlRequest();
            importRequest.CustomizationXml = ImportFile;
            service.Execute(importRequest);

            Project.Log(Level.Info, "Deployment completed");

            if(Publish)
            {
                Project.Log(Level.Info, "About to publish");
                PublishAllXmlRequest request = new PublishAllXmlRequest();
                service.Execute(request);

                Project.Log(Level.Info, "Publish completed");
            }
        }
    }
}